var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: -1,
            type:"type"
        },
        key: {
            url:"nourl"
        }
    },
    check:{
        enable:true,
        nocheckInherit:true
    }
};
var ztree;


function showAllNode(nodes){
    nodes = ztree.transformToArray(nodes);
    for(var i=nodes.length-1; i>=0; i--) {
        if(nodes[i].getParentNode()!=null){
            ztree.expandNode(nodes[i],false,false,false,false);
        }else{
            ztree.expandNode(nodes[i],true,true,false,false);
        }
        ztree.showNode(nodes[i]);
        showAllNode(nodes[i].children);
    }
}


function hideAllNode(nodes){
    nodes = ztree.transformToArray(nodes);
    for(var i=nodes.length-1; i>=0; i--) {
        ztree.hideNode(nodes[i]);
    }
}

function updateNodes(nodeList) {
    ztree.showNodes(nodeList);
    for(var i=0, l=nodeList.length; i<l; i++) {
        var treeNode = nodeList[i];
        showChildren(treeNode);
        showParent(treeNode)
    }
}
function showChildren(treeNode){
    if (treeNode.isParent){
        for(var idx in treeNode.children){
            var node = treeNode.children[idx];
            ztree.showNode(node);
            showChildren(node);
        }
    }
}
function showParent(treeNode){
    var parentNode;
    while((parentNode = treeNode.getParentNode()) != null){
        ztree.showNode(parentNode);
        ztree.expandNode(parentNode, true, false, false);
        treeNode = parentNode;
    }
}

var jobId = T.p("jobId");
$(function () {
    $("#jqGrid").jqGrid({
        treeGrid: true,
        treeGridModel: 'adjacency', //treeGrid模式，跟json元数据有关 ,adjacency/nested
        ExpandColumn : 'workId',
        url: '../scheduleJobDtl/treelist',
        datatype: "json",
        postData:{jobId:jobId},
        colModel: [
			{ label: 'id', name: 'id', width: 50, key: true,hidden:true },
            { label: '作业', name: 'workId',index:'work_id', width: 80 , formatter: function (value, options, row) {
                  if("work" ===row.type){
                      return " <i class='fa fa-tasks'></i>  " + T.showDictDynaName('work',value);
                  }else if ("workSubject" ===row.type){
                      if(9999999999 === value){
                          return " <i class='fa fa-object-group'></i>  " +"无归属专题";
                      }
                      return " <i class='fa fa-object-group'></i>  " + T.showDictDynaName('subject',value);
                  }

            }},
			{ label: '类型', name: 'type',index:'type', width: 80 , formatter: function (value, options, row) {
                    return T.showDictItemName('workType',value);
                }},
			{ label: '执行顺序', name: 'orderNum',index:'order_num', width: 80,  formatter: function(val, obj, row, act){
                    var html = [];
                    html.push('<input type="hidden" name="ids"  value="'+row.id+'"/>');
                    html.push('<input name="sorts"  type="number" value="'+row.orderNum+'" style="width:50px;height:19px;margin:0;padding:0;text-align:center;border:1px solid #ddd">');
                    return html.join('');
			}},
            { label:'操作', name:'actions', sortable:false,width:20,formatter:function (value, options, row, act) {
                    var opts =  [];
                    if (row.type == 'workSubject'){
                        opts.push('<a href="javascript:" class="btnList" title="删除专题" data-confirm="确认要删除该专题及其所属作业项吗？" data-click="vm.del(\''+row.id+'\')"><i class="fa fa-trash-o"></i></a>&nbsp;');
                    }
                    if (row.type == 'work'){
                        opts.push('<a href="javascript:" class="btnList" title="删除作业项" data-confirm="确认要删除该作业项吗？" data-click="vm.del(\''+row.id+'\')"><i class="fa fa-trash-o"></i></a>&nbsp;');
                    }
                    return opts.join('');
                }
            }
        ],
		viewrecords: true,
        height: 800,
        // rowNum: 20,
        // rowList : [20,30,50],
        // rownumbers: true,
        // rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        //pager: "#jqGridPager",
        jsonReader : {
            root: "resData"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        treeReader : {
            level_field: "level",
            parent_id_field: "parentId",
            leaf_field: "leaf",
            expanded_field: "open"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	//$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        },
        loadComplete:function () {
            btnMoreEventBind();
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		isShowCond:false,
        btnText:'查询',
        editSort:{
            ids :[],
            sorts :[]
        },
        qryForm:{
        },
        searchName:'',
        zNodes:[],
        checkedNodes:[],
        jobDtlTree:{}
	},
    mounted:function(){
        //加载作业项树
        this.initialZtree();
    },
	methods: {
        initialZtree :function () {
            $.get("../scheduleJobDtl/itemTreelist",{jobId:jobId}, function(r){
                vm.zNodes = r.resData;
                ztree =$.fn.zTree.init($("#workItemTree"), setting, vm.zNodes);
            })

        },
        autoMatch:function () {
            var nodes = ztree.getNodes();
            var value = $.trim(this.searchName);
            if (value.length > 0) {
                hideAllNode(nodes);
                var nodeList = ztree.getNodesByParamFuzzy("name", value);
                updateNodes(nodeList);
            }else {
                showAllNode(nodes);
                return;
            }

        },
        updateSort:function(){
            var ids =[];
            $("input[name='ids']").each(function () {
                ids.push($(this).val());
            })
            var sorts = [];
            $("input[name='sorts']").each(function () {
                sorts.push($(this).val());
            })
            this.editSort.ids = ids;
            this.editSort.sorts = sorts;
            $.ajax({
                type: "POST",
                url: "../scheduleJobDtl/updateSort",
                data: this.editSort,
                contentType:'application/x-www-form-urlencoded; charset=UTF-8',
                traditional: true,
                dataType: "json",
                success: function(r){
                    if(r.code == 0){
                        alert('操作成功', function(index){
                            $("#jqGrid").trigger("reloadGrid");
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });

        },
		reset: function(){

        },
        query: function () {
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{
                },
                page:1
            }).trigger("reloadGrid");
        },
        toggle:function(){
            this.isShowCond = !this.isShowCond;
            if(this.isShowCond==true){
                this.btnText = "隐藏"
            }else if(this.isShowCond==false){
                this.btnText = "查询"
            }
        },
		del: function (id) {
			if(id == null){
                id = getSelectedRow();
                if(id == null){
                    return ;
                }
			}
			var ids = [id];
				$.ajax({
					type: "POST",
				    url: "../scheduleJobDtl/delete",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
		},back:function (event) {
            history.go(-1);
        },addWorkSubject:function () {
            this.initialZtree();
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-lan',
                title: "选择作业",
                area: ['400px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#workItemLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    //获取选择的菜单
                    var nodes = ztree.getCheckedNodes(true);
                    var idList = new Array();
                    for(var i=0; i<nodes.length; i++) {
                        idList.push(nodes[i].id);
                    }
                    vm.checkedNodes = idList;
                    console.log(nodes);
                    console.log(vm.checkedNodes);
                    vm.jobDtlTree = {jobId:jobId,itemTrees:nodes};
                    layer.close(index);
                    $.ajax({
                        type: "POST",
                        url: "../scheduleJobDtl/saveItemTree",
                        data: JSON.stringify(vm.jobDtlTree),
                        success: function(r){
                            if(r.code === 0){
                                alert('操作成功', function(index){
                                    $("#jqGrid").trigger("reloadGrid");
                                });
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                }
            });
        }
	}
});
